var validator = require('validator');
var _ = require('lodash');
var { request, summary, body, description, tags } = require('koa-swagger-decorator');
var Version = require('../Models/Version');
var TestRecord = require('../Models/TestRecord');
var jiraDbModel = require('../Models/jiraDbModel');
var logTool = require('../Tools/LogTool');

var globalResponseCode = require('../base/ResponseCode');
var versionResponseCode = {
  VERSION_ALREADY_EXIST: { code: 40001, message: '版本号已存在！' },
  VERSION_NOT_EXIST:  { code: 40002, message: '版本号不存在！' },
  DELETE_FAIL_EXIST_RECORD: { code: 40003, message: '版本下存在提测记录，不可删除' },
  UPDATE_TEST_TIME_FAIL_EXIST_RECORD: {code:40004, message:'版本下存在提测记录，不可修改提测时间'},
  ADD_FAIL:{code:40005, message:'添加失败：项目ID错误！'},

};

class VersionController {

  @tags(['Version'])
  @request('post', '/version/add')
  @summary('添加版本')
  @description('只有测试人员可添加版本')
  @body(
    {
      projectId: { type: 'int', required: true, example: 4 },
      name: { type: 'string', required: true, example: 'v5.0.0-beta.4.1', description: '版本号' },
      expectVersionReleaseTime: { type: 'date', required: true, example: '2018-08-10' },
      expectTestTime: { type: 'date', required: true, example: '2018-07-26' },
      selfTestCaseUrl: { type: 'string', required: true, example: "http://192.168.2.10:8081/testlink/index.php?caller=login&viewer=" }
    }
  )
  async addVersion(ctx) {
    try {
      if (ctx.session.user) {

        if (ctx.session.user.roleId !== 3 && ctx.session.user.roleId !== 4) {
          return ctx.body = globalResponseCode.NO_AUTH;
        }
        let version = ctx.request.body;
        
        if (!version || !version.name || !version.expectTestTime ||
          !version.expectVersionReleaseTime || !version.selfTestCaseUrl ||
          !version.projectId) {
          return ctx.body = globalResponseCode.PARAMS_ERROR;
        }
        
        if (!validator.isISO8601(version.expectTestTime) || !validator.isISO8601(version.expectVersionReleaseTime)) {
          
          return ctx.body = globalResponseCode.PARAM_DATE_FORMAT_ERROR;
        }
        version.providerUserId = ctx.session.user.id;
        version.createrealname=ctx.session.user.realName;
       // console.log('%%%%%',version)
        let versionId = await Version.insert(version);
    
        if(versionId !== 0){
          return ctx.body = _.merge({}, globalResponseCode.SUCCESS, { data: { versionId: versionId } })
        }else{
          return ctx.body = versionResponseCode.ADD_FAIL;
        }
      } else {
        return ctx.body = globalResponseCode.NO_LOGIN;
      }
    } catch (error) {
      if (error.errno == 1062) {
        return ctx.body = versionResponseCode.VERSION_ALREADY_EXIST;
      }
      console.log(error)
      logTool.logError(ctx, error);
      return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
    }
  }

  @tags(['Version'])
  @request('post', '/version/update')
  @summary('修改版本')
  @description('可修改项：版本名，发布时间、首次提测时间、自测用例地址')
  @body({
    id: { type: "int", required: true, example: 32, description: '版本id' },
    name: { type: 'string', required: false, example: 'v5.0.0-beta.4.1', description: '版本号' },
    expectVersionReleaseTime: { type: 'date', required: false, example: '2018-08-10' },
    expectTestTime: { type: 'date', required: false, example: '2018-07-26' },
    selfTestCaseUrl: { type: 'string', required: false, example: "http://192.168.2.10:8081/testlink/index.php?caller=login&viewer=" }
  })
  async updateVersion(ctx) {
    try {
      if (ctx.session.user) {
        if (ctx.session.user.roleId !== 3 && ctx.session.user.roleId !== 4) {
          return ctx.body = globalResponseCode.NO_AUTH;
        }
        let version = ctx.request.body;
        if (!version.id || !_.isInteger(version.id)) {
          return ctx.body = globalResponseCode.PARAMS_ERROR;
        }
        if (_.keys(version).length <= 1) {
          return ctx.body = globalResponseCode.PARAMS_ERROR;
        }

        if (version.expectTestTime) {
          let record_count = await Version.queryRecordCountByVerisonId(version.id);
          if(record_count > 0){
            return ctx.body = versionResponseCode.UPDATE_TEST_TIME_FAIL_EXIST_RECORD;
          }
        }
        let result = await Version.update(version);
        if(version.name){
          let result = await TestRecord.updateVersionNameByVersionId(version.id, version.name);
        }
        return ctx.body = result ? globalResponseCode.SUCCESS : versionResponseCode.VERSION_NOT_EXIST;
      } else {
        return ctx.body = globalResponseCode.NO_LOGIN;
      }
    } catch (error) {
      if (error.errno == 1062) {
        return ctx.body = versionResponseCode.VERSION_ALREADY_EXIST;
      }
      logTool.logError(ctx, error);
      return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
    }
  }

  @tags(['Version'])
  @request('delete', '/version/delete')
  @summary('删除版本')
  @description('1.版本下存在提测记录时，不可删除\n 2.只有测试人员和管理员可删除')
  @body(
    {
      id: { type: 'int', required: true, example: 1 }
    }
  )
  async deleteVersionById(ctx) {
    try {
      if (ctx.session.user) {
        if (ctx.session.user.roleId !== 3 && ctx.session.user.roleId !== 4) {
          return ctx.body = globalResponseCode.NO_AUTH;
        }
        if (!ctx.request.body.id && !_.isInteger(ctx.request.body.id)) {
          return ctx.body = globalResponseCode.PARAMS_ERROR;
        }
        let versionId = ctx.request.body.id;
        let recordCount = await TestRecord.queryTestRecordCountByVersionId(versionId);
        if (recordCount > 0) {
          return ctx.body = versionResponseCode.DELETE_FAIL_EXIST_RECORD;
        }
        let result = await Version.deleteById(versionId);
        if(result){
          return ctx.body = globalResponseCode.SUCCESS;
        }else{
          return ctx.body = versionResponseCode.VERSION_NOT_EXIST;
        }
      } else {
        return ctx.body = globalResponseCode.NO_LOGIN;
      }
    } catch (error) {
      logTool.logError(ctx, error);
      return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
    }
  }

  @tags(['Version'])
	@request('post', '/version/getProjectVersionList')
	@summary('获取项目最新5个符合规范的版本号')
	@body({
		pname: { type: 'string', require: true, example: 2, description: '项目名称' },
	})

	async getVersionList(ctx){
		try{
			if(ctx.session.user){
				let pname = ctx.request.body.pname
				if(pname){
					let verlist = await jiraDbModel.jiraDbVersionList(pname);
					return ctx.body = _.merge({}, globalResponseCode.SUCCESS, {data:verlist});
				}
			}else {
				return ctx.body = globalResponseCode.NO_LOGIN;
			}
		}catch(error){
      console.log(error)
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;	
		}
	}
}

module.exports = new VersionController();
